package com.lnj.community.service.Impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.HighlightField;
import com.lnj.community.dao.entity.DiscussPost;
import com.lnj.community.elasticsearch.DiscussPostRepository;
import com.lnj.community.service.ElasticsearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ElasticsearchServiceImpl implements ElasticsearchService {
    @Autowired
    private ElasticsearchClient elasticsearchClient;
    @Autowired
    private DiscussPostRepository discussRepository;

    @Override
    public void saveDiscussPost(DiscussPost discussPost) {
        discussRepository.save(discussPost);
    }

    @Override
    public void deleteDiscussPost(int id) {
        discussRepository.deleteById(id);
    }

    @Override
    public Page<DiscussPost> searchDiscussPost(String keyword, int current, int limit) {
        //构建搜索请求条件
        SearchRequest searchRequest = SearchRequest.of(s -> s
                .index("discusspost") // 替换为你的索引名
                .query(q -> q
                        .multiMatch(m -> m
                                .query(keyword)
                                .fields("title", "content")
                        )
                )
                .sort(so -> so.field(f -> f.field("type").order(SortOrder.Desc)))
                .sort(so -> so.field(f -> f.field("score").order(SortOrder.Desc)))
                .sort(so -> so.field(f -> f.field("createTime").order(SortOrder.Desc)))
                .from(0)
                .size(10)
                .highlight(h -> h
                        .fields("title", HighlightField.of(hf -> hf.preTags("<em>").postTags("</em>")))
                        .fields("content", HighlightField.of(hf -> hf.preTags("<em>").postTags("</em>")))
                )
        );

        // 执行搜索
        SearchResponse<DiscussPost> response = null;
        try {
            response = elasticsearchClient.search(searchRequest, DiscussPost.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 处理结果
        List<DiscussPost> posts = response.hits().hits().stream()
                .map(hit -> {
                    DiscussPost post = hit.source();
                    // 处理高亮结果
                    if (hit.highlight() != null) {
                        if (hit.highlight().containsKey("title")) {
                            post.setTitle(String.join("", hit.highlight().get("title")));
                        }
                        if (hit.highlight().containsKey("content")) {
                            post.setContent(String.join("", hit.highlight().get("content")));
                        }
                    }
                    return post;
                })
                .collect(Collectors.toList());

        // 创建分页结果
        Page<DiscussPost> page = new PageImpl<>(
                posts,
                PageRequest.of(current, limit),
                response.hits().total().value()
        );

        return page;
    }

}
